﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Collections.Specialized;
using MySql.Data.MySqlClient;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Contexts;
using System.Security.Cryptography;
using Google.Protobuf.WellKnownTypes;

namespace GeodeticCoordinates
{
    public partial class Form_one : Form
    {
        public Form_one()
        {
            InitializeComponent();
        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        int Gindex = 0;
        int Dindex = 1;
        public void AddColumnHead(int n)
        {
            listView_dadikongjian.Columns.Clear();
            ColumnHeader h1 = new ColumnHeader();
            ColumnHeader h2 = new ColumnHeader();
            ColumnHeader h3 = new ColumnHeader();
            ColumnHeader h4 = new ColumnHeader();
            ColumnHeader h5 = new ColumnHeader();
            ColumnHeader h6 = new ColumnHeader();

            if (n == 0)
            {
                h1.Text = "序号 ";
                h2.Text = "点名";
                h3.Text = "高斯坐标x ";
                h4.Text = "高斯坐标y";
                h5.Text = "纬度B(dms)";
                h6.Text = "经度L(dms)";
            }

            else if (n == 1)
            {
                h1.Text = "序号 ";
                h2.Text = "点名";
                h3.Text = "纬度B(dms)";
                h4.Text = "经度L(dms)";
                h5.Text = "高斯坐标x";
                h6.Text = "高斯坐标y";
            }
            else if (n == -1)
            {
                h1.Text = "序号 ";
                h2.Text = "点名";
                h3.Text = "高斯坐标（6度带）x";
                h4.Text = "高斯坐标（6度带）y";
                h5.Text = "高斯坐标（3度带）x";
                h6.Text = "高斯坐标（3度带）y";
            }
            else
            {
                return;
            }
            listView_dadikongjian.Columns.Add(h1);
            listView_dadikongjian.Columns.Add(h2);
            listView_dadikongjian.Columns.Add(h3);
            listView_dadikongjian.Columns.Add(h4);
            listView_dadikongjian.Columns.Add(h5);
            listView_dadikongjian.Columns.Add(h6);
        }

        private void AddToListview(string[][] str2)
        {
            this.listView_dadikongjian.Items.Clear(); //清空listview1中所有数据

            // 添加数据到listview中
            for (int i = 0; i < str2.Length; i++)
            {
                ListViewItem b = new ListViewItem();
                b.SubItems[0].Text = (i + 1).ToString();
                b.SubItems.Add(str2[i][0]);
                b.SubItems.Add(str2[i][1]);
                b.SubItems.Add(str2[i][2]);
                b.SubItems.Add("");
                b.SubItems.Add("");
                listView_dadikongjian.Items.Add(b);
            }
        }
        private void 导入高斯坐标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddColumnHead(Gindex);
            // Gindex += 2;

            // 创建对象，调用导入文件的函数
            operateFiles add1 = new operateFiles();
            string[][] str2 = add1.AddFiles();

            AddToListview(str2);

            #region addtolistview
            //this.listView_dadikongjian.Items.Clear(); //清空listview1中所有数据
            //// 添加数据到listview中
            //for (int i = 0; i < str2.Length; i++)
            //{
            //    ListViewItem b = new ListViewItem();
            //    b.SubItems[0].Text = (i + 1).ToString();
            //    b.SubItems.Add(str2[i][0]);
            //    b.SubItems.Add(str2[i][1]);
            //    b.SubItems.Add(str2[i][2]);
            //    b.SubItems.Add("");
            //    b.SubItems.Add("");
            //    listView_dadikongjian.Items.Add(b);
            //} 
            #endregion
        }

        private void splitContainer_bottom1_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }



        public void comboBox_selectEllipsoid_SelectedIndexChanged(object sender, EventArgs e)
        {
            EllipsoidParameters e1 = new EllipsoidParameters();
            string[] ellispe = e1.SetEllipse(comboBox_selectEllipsoid.SelectedIndex); //获得当前椭球索引

            textBox_EllipsoidName.Text = ellispe[0];
            textBox_Longhalfaxis.Text = ellispe[1];
            textBox_Shorthalfaxis.Text = ellispe[2];
            textBox_power_e1.Text = ellispe[3]; //输出第一偏心率
            textBox_power_e2.Text = ellispe[4];
            textBox_Flattening.Text = ellispe[5]; //计算扁率f
            textBox_RadiusOfExtremecurvature.Text = ellispe[6]; //计算极曲率半径

            textBox_EllipsoidName.Enabled = false;
            textBox_Longhalfaxis.Enabled = false;
            textBox_Shorthalfaxis.Enabled = false;
            textBox_power_e1.Enabled = false;
            textBox_power_e2.Enabled = false;
            textBox_Flattening.Enabled = false;
            textBox_RadiusOfExtremecurvature.Enabled = false;
        }

        bool mousemove_flag = false;
        private void button_calzhengsuan_Click(object sender, EventArgs e)
        {
            mousemove_flag = true;
            Calculate calculate = new Calculate();
            calculate.CalXishu(Convert.ToDouble(textBox_power_e1.Text));
            int[] re = setParameters.XX();
            calculate.n = re[0];

            for (int i = 0; i < listView_dadikongjian.Items.Count; i++)
            {
                if (listView_dadikongjian.Items[i].SubItems[0].Text == "")
                {
                    break;
                }
                else
                {
                    double[] result = calculate.CalLonLatToGaosi(
                                Convert.ToDouble(listView_dadikongjian.Items[i].SubItems[2].Text),
                                Convert.ToDouble(listView_dadikongjian.Items[i].SubItems[3].Text),
                                Convert.ToDouble(textBox_Longhalfaxis.Text),
                                Convert.ToDouble(textBox_power_e1.Text),
                                Convert.ToDouble(textBox_power_e2.Text));

                    listView_dadikongjian.Items[i].SubItems[4].Text = result[0].ToString("f6");
                    listView_dadikongjian.Items[i].SubItems[5].Text = result[1].ToString("f6");
                }
            }
        }

        bool flag = true;
        private void button_calfansuan_Click(object sender, EventArgs e)
        {
            mousemove_flag = true;
            Calculate calculate = new Calculate();
            calculate.CalXishu(Convert.ToDouble(textBox_power_e1.Text));
            if (flag)
            {
                int[] re = setParameters.XX();
                calculate.n = re[0]; // 3 or 6
                calculate.n0 = re[1]; //带号
            }
            for (int i = 0; i < listView_dadikongjian.Items.Count; i++)
            {
                if (listView_dadikongjian.Items[i].SubItems[0].Text == "")
                {
                    break;
                }
                else
                {
                    if (flag)
                    {
                        double[] result = calculate.CalGaosiToLonLat(
                                Convert.ToDouble(listView_dadikongjian.Items[i].SubItems[2].Text),
                                Convert.ToDouble(listView_dadikongjian.Items[i].SubItems[3].Text),
                                Convert.ToDouble(textBox_Longhalfaxis.Text),
                                Convert.ToDouble(textBox_power_e1.Text));

                        listView_dadikongjian.Items[i].SubItems[4].Text = result[0].ToString("f6");
                        listView_dadikongjian.Items[i].SubItems[5].Text = result[1].ToString("f6");
                    }
                    else
                    {
                        AddColumnHead(-1);
                        calculate.n = setParameters.pos; // 3 or 6
                        calculate.n0 = setParameters.n0; // 带号
                        double[] result = calculate.CalGaosiToLonLat(
                                Convert.ToDouble(listView_dadikongjian.Items[i].SubItems[2].Text),
                                Convert.ToDouble(listView_dadikongjian.Items[i].SubItems[3].Text),
                                Convert.ToDouble(textBox_Longhalfaxis.Text),
                                Convert.ToDouble(textBox_power_e1.Text));
                        double[] result_fansuan = calculate.CalLonLatToGaosi(
                                result[0], result[1],
                                Convert.ToDouble(textBox_Longhalfaxis.Text),
                                Convert.ToDouble(textBox_power_e1.Text),
                                Convert.ToDouble(textBox_power_e2.Text));

                        listView_dadikongjian.Items[i].SubItems[4].Text = result_fansuan[0].ToString("f6");
                        listView_dadikongjian.Items[i].SubItems[5].Text = result_fansuan[1].ToString("f6");
                    }
                }
            }
        }

        private void 选择大地坐标文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddColumnHead(Dindex);
            // Dindex += 2;
            // 创建对象，调用导入文件的函数
            operateFiles add1 = new operateFiles();
            string[][] str2 = add1.AddFiles();

            AddToListview(str2);

            #region addtolistview
            //this.listView_dadikongjian.Items.Clear(); //清空listview1中所有数据
            //// 添加数据到listview中
            //for (int i = 0; i < str2.Length; i++)
            //{
            //    ListViewItem b = new ListViewItem();
            //    b.SubItems[0].Text = (i + 1).ToString();
            //    b.SubItems.Add(str2[i][0]);
            //    b.SubItems.Add(str2[i][1]);
            //    b.SubItems.Add(str2[i][2]);
            //    b.SubItems.Add("");
            //    b.SubItems.Add("");
            //    listView_dadikongjian.Items.Add(b);
            //} 
            #endregion
        }

        public void LuRUData(double n, string point, string latitude, string lontitude)
        {
            ListViewItem b = new ListViewItem((n + 1).ToString());
            b.SubItems.Add(point);
            b.SubItems.Add(latitude);
            b.SubItems.Add(lontitude);
            b.SubItems.Add("");
            b.SubItems.Add("");
            listView_dadikongjian.Items.Add(b);
        }

        private void button_luruzhengsuan_Click(object sender, EventArgs e)
        {
            AddColumnHead(Dindex);
            Dindex += 2;

            LuRUData(listView_dadikongjian.Items.Count, textBox_gaosidianming01.Text, textBox_gaosilat.Text, textBox_gaosilon.Text);
        }

        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 将listview所有数据利用二维数组存储起来
            string[,] data = new string[listView_dadikongjian.Items.Count, 6]; // 初始化二维数组

            for (int m = 0; m < listView_dadikongjian.Items.Count; m++)  //所有项的集合数
            {
                for (int n = 0; n < 6; n++)   // 一个项的所有子项集合数 
                {
                    if (listView_dadikongjian.Items[m].SubItems[n].Text == null) //遇到空的项则结束该次循环
                    {
                        break;
                    }

                    data[m, n] = listView_dadikongjian.Items[m].SubItems[n].Text;
                }
            }

            // 初始化操作文件的类并调用导出文件的函数
            operateFiles op = new operateFiles();
            op.ExportFiles(listView_dadikongjian.Items.Count, data);

        }

        private void button_luufansuan_Click(object sender, EventArgs e)
        {
            AddColumnHead(Gindex);
            Gindex += 2;

            LuRUData(listView_dadikongjian.Items.Count, textBox_gaosidianming02.Text, textBox_gaosipingmian_x.Text, textBox_gaosipingmian_y.Text);
        }

        private void 导出数据库数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            AddColumnHead(1);

            this.listView_dadikongjian.Items.Clear();
            operateDatabase operate = new operateDatabase();
            operate.Builder = operate.GetData(1);
            operate.Connection = new MySqlConnection(operate.Builder.ConnectionString);

            try
            {
                operate.Connection.Open();
                string sql = "select * from " + operate.mysqltableName + ";";
                MySqlCommand cmd = new MySqlCommand(sql, operate.Connection);
                MySqlDataReader reader = cmd.ExecuteReader();//执行查询

                int count = 0;
                while (reader.Read())
                {

                    ListViewItem lt = new ListViewItem();

                    lt.SubItems[0].Text = (++count).ToString();
                    lt.SubItems.Add(reader["pointName"].ToString());
                    lt.SubItems.Add(reader["latitude（dms）"].ToString());
                    lt.SubItems.Add(reader["lontitude（dms）"].ToString());
                    lt.SubItems.Add("");
                    lt.SubItems.Add("");

                    listView_dadikongjian.Items.Add(lt);
                }
                MessageBox.Show("查询成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                operate.Connection.Close();
            }
        }

        private void 导入至数据库ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operateDatabase operateDatabase = new operateDatabase();

            operateDatabase.DeleteMysqlTable();
            bool issucess = operateDatabase.CreatedMysqlTable();
            if (issucess)
            {
                MessageBox.Show("导入成功！");
            }
        }

        SetParameters setParameters = new SetParameters();
        private void 设置参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setParameters.ShowDialog();
            comboBox_selectEllipsoid_VisibleChanged(sender, e);
        }

        private void 计算换带结果ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mousemove_flag = true;
            flag = false;
            button_calfansuan_Click(sender, e);

        }

        private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 另存为AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            导出ToolStripMenuItem.PerformClick();
        }

        private void 保存SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            导出ToolStripMenuItem.PerformClick();
        }

        private void 打开OToolStripButton_Click(object sender, EventArgs e)
        {
            导入高斯坐标ToolStripMenuItem.PerformClick();
        }

        private void 保存SToolStripButton_Click(object sender, EventArgs e)
        {
            导出ToolStripMenuItem.PerformClick();
        }

        static string path = @"D:\";    //源文件路径
        private void 新建NToolStripButton_Click(object sender, EventArgs e)
        {
            //参数1：指定要判断的文件路径
            if (!File.Exists(path))
            {
                //参数1：要创建的文件路径，包含文件名称、后缀等
                FileStream fs = File.Create(path);
                fs.Close();
                MessageBox.Show("文件创建成功！");
            }
            else
            {
                MessageBox.Show("文件已经存在！");
            }
        }

        private void 数据库操作ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void button_clear_Click(object sender, EventArgs e)
        {
            this.listView_dadikongjian.Clear();
        }

        private void 导出计算成果数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void listView_dadikongjian_MouseDown(object sender, MouseEventArgs e)
        {
            if (mousemove_flag)
            {
                this.contextMenuStrip_LtQuickClick.Enabled = false;
            }
            else
            {
                if (e.Button == MouseButtons.Right)
                {
                    var hitTestInfo = listView_dadikongjian.HitTest(e.X, e.Y);

                    if (hitTestInfo.Item != null)
                    {
                        var loc = e.Location;
                        //var lo = splitContainer_bottom1.Panel2.Location;
                        //loc.Offset(listView_dadikongjian.Location);
                        loc.Offset(splitContainer_bottom1.Panel2.Location);
                        this.contextMenuStrip_LtQuickClick.Show(this, loc);
                    }
                }
            }
        }

        private void contextMenuStrip_LtQuickClick_Opening(object sender, CancelEventArgs e)
        {

        }

        UpdateDatabase updata = new UpdateDatabase();
        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            updata.ShowDialog();
            double up_lon = updata.Update_longitude;
            double up_lat = updata.Update_latitude;
            int ipos = listView_dadikongjian.Items.IndexOf(listView_dadikongjian.FocusedItem);
            operateDatabase op_update = new operateDatabase();
            op_update.sql = "update " + op_update.mysqltableName + " set latitude（dms） = '" + up_lat + "',lontitude（dms） = '" + up_lon + "' where pointName ='" + listView_dadikongjian.Items[ipos].SubItems[1].Text+"';";
            op_update.UpdateDate();
            导出数据库数据ToolStripMenuItem.PerformClick();
        }

        private void 查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int ipos = listView_dadikongjian.Items.IndexOf(listView_dadikongjian.FocusedItem);
            operateDatabase op_delete = new operateDatabase();
            op_delete.sql = "delete from " + op_delete.mysqltableName + " where pointName = '" + listView_dadikongjian.Items[ipos].SubItems[1].Text + "'";
            op_delete.DeleteDate();
            导出数据库数据ToolStripMenuItem.PerformClick();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            选择大地坐标文件ToolStripMenuItem.PerformClick();
        }

        private void Form_one_Load(object sender, EventArgs e)
        {

        }

        public bool combox_visable = true;

        private void comboBox_selectEllipsoid_VisibleChanged(object sender, EventArgs e)
        {
            combox_visable = setParameters.comvis;
            this.comboBox_selectEllipsoid.Enabled = combox_visable;
            if (combox_visable)
            {
                comboBox_selectEllipsoid_SelectedIndexChanged(this, e);
            }
            else
            {
                string[] other_ellispe = setParameters.ellispe;
                this.comboBox_selectEllipsoid.Text = other_ellispe[0];
                textBox_EllipsoidName.Text = other_ellispe[0];
                textBox_Longhalfaxis.Text = other_ellispe[1];
                textBox_Shorthalfaxis.Text = other_ellispe[2];
                textBox_power_e1.Text = other_ellispe[3]; //输出第一偏心率
                textBox_power_e2.Text = other_ellispe[4];
                textBox_Flattening.Text = other_ellispe[5]; //计算扁率f
                textBox_RadiusOfExtremecurvature.Text = other_ellispe[6]; //计算极曲率半径
            }
        }

        private void 帮助LToolStripButton_Click(object sender, EventArgs e)
        {
            new Assitance().ShowDialog();
        }
    }
}
